package com.yzkj.cpjxc.business.framework.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * Token 令牌生成类，给每一个Form表单生成令牌
 */
public class CSRFTokenManager {
	
	private CSRFTokenManager() { };

	/**
	 * 从Session中获取Token
	 */
	public static String getTokenForSession(HttpSession session) {
		
		String token = null;
		synchronized (session) {
			token = (String) session.getAttribute(Constants.CSRF_TOKEN_FOR_SESSION_ATTR_NAME);
			if (null == token) {
               token = UUID.randomUUID().toString();
               session.setAttribute(Constants.CSRF_TOKEN_FOR_SESSION_ATTR_NAME, token);
           }
       }
       return token;
   }

   /**
	* 根据CSRF_TOKEN_PARAM_NAME获取令牌值
	*/
	public static String getTokenFromRequest(HttpServletRequest request) {
		return request.getParameter(Constants.CSRF_TOKEN_PARAM_NAME);
	}

}

